<?php

class Ext_Image_Save_Adapter_Base
{
    protected $_datas    = array();
    protected $_messages = array();
    
    const RENAME_IMAGE_FAILED = 'renameImageFailed';
    protected $_messageTemplates = array(
        self::RENAME_IMAGE_FAILED => "Rename image failed.",
    );
    protected $_messager;
    
    public function __construct()
    {
        $this->_messager = new Ext_Messager($this->_messageTemplates);
    }

    public function save($file)
    {
        $result = array(
            'code'     => Ext_Image_Save_Result::FAILURE,
            'data'     => '',
            'messages' => array(),
        );

        $sourceMd5sum = md5_file($file);
        $image = App_Model_DbTable_Image::getInstance()->getRowByMd5sum($sourceMd5sum);
        if($image){
            $imageId = $image['id'];
            $result['code'] = Ext_Image_Save_Result::SUCCESS;
            $result['data'] = $imageId;
            return new Ext_Image_Save_Result($result['code'], $result['data'], $result['messages']);
        }

        $config = Ext_Config::getInstance()->getConfig('image');
        
        $fileDir  = rtrim($config->storage->base->destination, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
        $filePath = implode(DIRECTORY_SEPARATOR, array(date('Y'), date('m'), date('d'), date('H')));
        $filePath = Ext_Utility_File::preparePath($fileDir, $filePath);
        $fileExt  = Ext_Utility_File::getImageType($file);
        
        $sourceFileName = $sourceMd5sum. "." . $fileExt;
        $newFile  = rtrim($fileDir . $filePath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR.$sourceFileName;
        
        if(!copy($file, $newFile)){
            require_once 'Ext/Image/Save/Exception.php';
            throw new Ext_Image_Save_Exception("Rename image file failed.");
        }
        
        $imageBase = App_Model_DbTable_Image_Base::getInstance()->getRowByMd5sum($sourceMd5sum);
        if($imageBase){
            $sourceImageId = $imageBase['id'];
        }else{
            $row = array(
                'md5sum'     => $sourceMd5sum,
                'path'       => $filePath,
                'fileName'   => $sourceFileName,
                'createTime' => time(),
            );
            $sourceImageId = App_Model_DbTable_Image_Base::getInstance()->addNew($row);
        }
        
        $insertImageRow = array(
            'md5sum' => $sourceMd5sum,
            'source' => $sourceImageId,
        );
        
        $resizer = new Ext_Image_Save_Resize($file);

        $config = Ext_Config::getInstance()->getConfig('image');
        foreach($config->photo->size as $sizeName=>$size){
            $resizeFile = $resizer->resize($sizeName);
            $resizeMd5sum = md5_file($resizeFile);
            
            if($sourceMd5sum == $resizeMd5sum){
                $resizeImageId = $sourceImageId;
                $insertImageRow[$sizeName] = $resizeImageId;
                @unlink($resizeFile);
                continue;
            }
            
            $imageBase = App_Model_DbTable_Image_Base::getInstance()->getRowByMd5sum($resizeMd5sum);
            if($imageBase){
                $resizeImageId = $imageBase['id'];
                $insertImageRow[$sizeName] = $resizeImageId;
                @unlink($resizeFile);
                continue;
            }
            
            $resizeFileName = $sourceMd5sum. "_".$sizeName.".". $fileExt;
            $newFile  = rtrim($fileDir . $filePath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR.$resizeFileName;
            if(!@rename($resizeFile, $newFile)){
                require_once 'Ext/Image/Save/Exception.php';
                throw new Ext_Image_Save_Exception("Rename image file failed.");
            }
            $row = array(
                'md5sum'     => $resizeMd5sum,
                'path'       => $filePath,
                'fileName'   => $resizeFileName,
                'createTime' => time(),
            );
            $resizeImageId = App_Model_DbTable_Image_Base::getInstance()->addNew($row);
            $insertImageRow[$sizeName] = $resizeImageId;
        }
        $imageId = App_Model_DbTable_Image::getInstance()->addNew($insertImageRow);

        @unlink($file);
        
        $result['code'] = Ext_Image_Save_Result::SUCCESS;
        $result['data'] = $imageId;
        return new Ext_Image_Save_Result($result['code'], $result['data'], $result['messages']);

    }
}
